﻿using System.Web.Mvc;
using good1.ApplicationServices.Interface;
using good1.Web.Model;
using SharpArch.Core;

namespace good1.Web.Controllers
{
    public class LoginController : BaseController
    {

        public LoginController(IAuthenticationService authenticationService, ISecurityContextService securityContext) : base(securityContext)
        {
            Check.Require(authenticationService != null, "authenticationService may not be null");
            this.authenticationService = authenticationService;
        }

        public ActionResult Index()
        {
            LoginForm loginForm = new LoginForm {Message = TempData["message"]==null ?  "" : TempData["message"].ToString()};
            return View(loginForm);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Authenticate(LoginForm loginForm, string returnUrl)
        {
            if(authenticationService.ValidateUser(loginForm.Email, loginForm.Password))
            {
                SecurityContext.LogIn(loginForm.Email, loginForm.RememberMe);
                return string.IsNullOrEmpty(returnUrl) ? Redirect("/Home") : Redirect(returnUrl);
            }
            TempData["message"] = "The username and password supplied are not valid.";          
            return RedirectToAction<LoginController>(c => c.Index());
        }
       
        private readonly IAuthenticationService authenticationService;
    }
}
